<?php
require_once(DIR_LIBRARY."orm".DS."orm.php");
/**
 * this is common thread post framework for thread and post application
 *
 */
class CtpThreadDetail extends ORM
{
    const APP_NICE  = 1;
    const APP_FORUM = 2;
    const STATUS_AVAILABLE = 1;
    const STATUS_DELETED   = 2;

    public static $apps = array(
        "nice"  => self::APP_NICE,    
        "forum" => self::APP_FORUM,
    );

    private static $instance;

    protected $dsn       = "default";
    protected $tablename = "thread";

    public function __construct($id = NULL)
    {
        parent::__construct($id);
    }

    public function create()
    {
        //check  first
        $app      = $this->getApp();
        $creator  = $this->getCreator();

        if (!$app)
        {
            throw new Exception("no app");
        }

        if (!$creator)
        {
            throw new Exception("no creator");
        }

        $time = time();

        $sequence = self::factory()->getMax("sequence") + 1;
        $shard    = $this->generateShard($app, $time);
        $this->setSequence($sequence);
        $this->setShard($shard);
        $this->setStatus(self::STATUS_AVAILABLE);
        $this->setCreated($time);
        $this->setUpdated($time);

        //create
        return parent::create();
    }

    public function update()
    {
        $time = time();
        $this->setUpdated($time);
        
        //update
        return parent::update();
    }

    public function delete()
    {
        $this->setStatus(self::STATUS_DELETED);

        return parent::update();
    }

    private function generateShard($app, $time)
    {
        return $app;
    }

    public static function factory($id = NULL)
    {
        return new self($id);
    }

    public static function getInstance()
    {
        if (!self::$instance)
        {
            self::$instance = new self();
        }

        return self::$instance;
    }
    
} //end class
